package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        MinioClient minioClient = MinioClient.builder()
                                    .endpoint(endpointUrl)
                                    .credentials(accessKey,secreKey)
                                    .build();
        //判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!found){
            //桶不存在 创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }else {
            System.out.println("Bucket 'asiatrip' already exists.");
        }
        //声明文件名
        String filename = System.currentTimeMillis()+ UUID.randomUUID().toString();
        //设置文件后缀名截取
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        System.out.println("extension = " + extension);
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
                            file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType()).build());

        //  System.out.println("name:\t"+ file.getName());
        //  获取图片返回路径
        String url = endpointUrl+"/"+bucketName+"/"+filename;

        return Result.ok(url);
    }
}
